# （2）在不同通信半径下，判断连通率与节点数目的关系
import numpy as np
import matplotlib.pyplot as plt
import randomGraph
import generateMatrix
import time


def demo02(list_radius, total_count):
    # 存放节点数量
    node_number = [n for n in range(1, 101)]
    # 每次的连通性结果
    per_res = np.zeros((len(list_radius), 100))

    for per_radius in list_radius:
        for nodeNumber in range(1, 101):
            # 计数
            count = 0
            # 迭代total_count次
            for i in range(0, total_count):
                # 每次迭代中网络都要重新随机生成
                # 根据结点数量随机生成单位面积中的网络
                graph = randomGraph.generate_graph_by_node(nodeNumber)
                # 根据随机网络节点生成初始化的邻接矩阵
                init_array = generateMatrix.get_matrix_by_graph_and_radius(graph, per_radius)
                # 如果网络全连通则count++
                _, is_bool = generateMatrix.check_n_is_link(init_array, nodeNumber)
                if is_bool:
                    count += 1
                print("step 2 => per_radius=", per_radius, ",nodeNumber=", nodeNumber, ",i=", i, "/", total_count)
            per_res[list_radius.index(per_radius)][nodeNumber - 1] = count / total_count
        print("通信半径为", per_radius, "计算完成")
    return per_res, node_number


# 绘制结果图
def show_result_02(node_number, list_radius, result_link_rate):
    # 曲线标记
    markers = ['+', 'o', 'x', '.', '*']
    colors = ['b', 'g', 'r', 'c', 'm']
    lines = []
    i = 0
    for r in list_radius:
        lines.append('r = ' + str(r))
    for data_list in result_link_rate:
        plt.plot(node_number, data_list, color=colors[i], marker=markers[i])
        i += 1
    # 曲线n=x
    plt.legend(lines, loc='upper right')
    plt.xlabel('Number of nodes')
    plt.ylabel('Connectivity')
    plt.title('Relationship between connectivity and communication radius')

    plt.show()


# 运行
def operate():
    time_start = time.time()  # 记录开始时间
    # 通信半径列表
    radius_list = [0.05, 0.15, 0.25, 0.35, 0.45]
    # 迭代次数
    totalCount = 1000
    # 获取返回值 连通性
    link_res, node_res = demo02(radius_list, totalCount)
    print(link_res)
    print(node_res)
    # 展示结果
    show_result_02(node_res, radius_list, link_res)

    time_end = time.time()  # 记录结束时间
    time_sum = time_end - time_start  # 计算的时间差为程序的执行时间，单位为秒/s
    print("已全部完成,共用时" + str(time_sum) + "s")
    print("##################################################")


if __name__ == '__main__':
    operate()
